package com.github.h4de5ing.kmp.rtk

import com.fazecast.jSerialComm.SerialPort

class RadioApp {
    private var sp: SerialPort? = null
    private var isOpen = false
    private var isConfig = false
    private var config = listOf(
        "+++".toByteArray(),
        "ATP0=00 433.000 433.000".toByteArray() + byteArrayOf(0x0D, 0x0A),
        "AT&W".toByteArray() + byteArrayOf(0x0D, 0x0A),
        "ATA".toByteArray() + byteArrayOf(0x0D, 0x0A)
    )

    fun start(configFinish: () -> Unit, log: (String) -> Unit, onChange: (ByteArray) -> Unit) {
        try {
            sp = SerialPort.getCommPort(if (osArch().contains("aarch64")) "ttysWK3" else radioUartName)
            isOpen = sp?.openPort() ?: false
            log("电台串口打开${sp?.systemPortName} ${if (isOpen) "成功" else "失败"}")
            sp?.setComPortParameters(38400, 8, 1, 0)
            sp?.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING, 1000, 0)
        } catch (e: Exception) {
            log("电台串口异常:${e.message}")
            e.printStackTrace()
        }
        setChangeUIString { write(it) }
        setConfigChange { isConfig = it }
        Thread {
            println("Thread------------------------radio uart")
            val readBuffer = ByteArray(2048)
            config.forEach {
                write(it)
                Thread.sleep(2000)
            }
            configFinish()
            while (true) {
                try {
                    val length = sp?.readBytes(readBuffer, readBuffer.size) ?: 0
                    if (length > 0) {
                        val data = readBuffer.copyOfRange(0, length)
                        val stringData = String(data)
                        println("电台收到数据:${stringData}")
                        if (isConfig) log(stringData)
                        onChange(data)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                Thread.sleep(100)
            }
        }.start()
    }

    fun write(byteArray: ByteArray) {
        try {
            sp?.writeBytes(byteArray, byteArray.size)
            println("电台写入:${String(byteArray)}")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}